<?php

namespace app\store\model\appointment;

use app\common\model\BaseModel;
use app\common\model\UploadFile as UploadFileModel;
use app\common\service\Order as OrderService;
use think\Db;
use app\common\model\AppointmentService as ServiceModel;

/**
 * 线下预约模型
 * Class PointsLog
 * @package app\store\model\user
 */
class Offline extends BaseModel
{
    protected $name = 'appointment_order';

    /**
     * 列表
     * @param $query
     * @return \think\Paginator
     */
    public function getList($query = [])
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);

        // 获取数据列表
        $list = $this->with('order_info,time,type')
            ->alias('offline')
            ->field('offline.order_id,offline.is_self,offline.user_name,offline.user_phone,offline.create_time,
            offline.address,offline.appointment_date,offline.status,
            offline.service_name,order.total_price,time.name time_name,type.name type_name, offline.id,offline.offline_name')
            ->join('order', 'offline.user_order_id = order.order_id', 'left')
            ->join('appointment_time time', 'time.time_id = offline.time_id', 'left')
            ->join('appointment_type type', 'type.type_id = offline.type_id', 'left')
            ->where('offline.is_delete', 0)
            ->where('offline.is_offline', 1)
            ->order(['offline.create_time' => 'desc'])
            ->paginate(10, false, [
                'query' => \request()->request()
            ])->each(function ($item, $key) {
                $item['user_name'] = !empty($item['user_name']) ? $item['user_name'] : '';
                $item['user_phone'] = !empty($item['user_phone']) ? $item['user_phone'] : '';
                $item['address'] = !empty($item['address']) ? $item['address'] : '';

                $item['total_price'] = !empty($item['total_price']) ? $item['total_price'] : 0;
                $item['total_price'] = !empty($item['total_price']) ? $item['total_price'] : 0;
                $item['total_price'] = !empty($item['total_price']) ? $item['total_price'] : 0;
                $item['time_name'] = !empty($item['time_name']) ? $item['time_name'] : '';

                $uploadFile = new UploadFileModel;

                $images = Db::name('appointment_image')->where(['order_id' => $item['id']])->field('id,image_id')->select();
                $images = collection($images)->toArray();
                foreach ($images as &$val) {
                    if ($val['image_id']) {
                        $image = $uploadFile->detail($val['image_id']);
                        $val['image'] = $image['file_path'];
                    }
                }

                $item['images'] = $images;
            });

        return $list;

    }

    public function getStatusTextAttr($value, $data)
    {
        $status = [1 => '未服务', 2 => '已服务', 3 => '取消服务'];
        return $status[$data['status']];
    }

    public function getIsSelfAttr($value)
    {
        $status = [0 => '否', 1 => '是'];
        return $status[$value];
    }

    public function getAppointmentDateTextAttr($value, $data)
    {

        return $data['appointment_date'] > 0 ? date("Y-m-d H:i", $data['appointment_date']) : '';
    }

    /**
     * 设置查询条件
     * @param $query
     */
    private function setWhere($query)
    {
        // 设置默认的检索数据
        $params = $this->setQueryDefaultValue($query, [
            'search' => '',
            'offline.service_id' => -1,
            'offline.status' => 0,
            'start_time' => '',
            'end_time' => '',
        ]);
        // 使用状态
        isset($params['status']) && $params['status'] > 0 && $this->where('offline.status', '=', $params['status']);

        // 用户查询
        if (!empty($params['search'])) {
//            $users = Db("user_address")->where('name|phone', 'like', '%' . $params['search'] . '%')->column('user_id');
            $this->where('offline.user_name|offline.user_phone', 'like', '%'.$params['search'].'%');
        }

        // 服务人员id
        isset($params['service_id']) && $params['service_id'] > 0 && $this->where('offline.service_id', '=', $params['service_id']);

        // 起始时间
        !empty($params['start_time']) && $this->where('offline.appointment_date', '>=', strtotime($params['start_time']));
        // 截止时间
        !empty($params['end_time']) && $this->where('offline.appointment_date', '<=', strtotime($params['end_time']));
    }

    /**
     * 关联订单表
     * @return \think\model\relation\HasOne
     */
    public function orderInfo()
    {
        $module = self::getCalledModule() ?: 'common';
        return $this->hasOne("app\\{$module}\\model\\Order", 'order_id', 'user_order_id');
    }

    /**
     * 关联订单表
     * @return \think\model\relation\HasOne
     */
    public function time()
    {
        $module = self::getCalledModule() ?: 'common';
        return $this->hasOne("app\\{$module}\\model\\appointment\\Time", 'time_id', 'time_id');
    }

    /**
     * 关联订单表
     * @return \think\model\relation\HasOne
     */
    public function type()
    {
        $module = self::getCalledModule() ?: 'common';
        return $this->hasOne("app\\{$module}\\model\\appointment\\Type", 'type_id', 'type_id');
    }

    /**
     * 添加预约
     * @param $data
     * @return bool|mixed
     */
    public function add($data)
    {
        if (!isset($data['user_name'])) {
            $this->error = '用户名称不能为空';
            return false;
        }

        if (!isset($data['user_phone'])) {
            $this->error = '用户手机号不能为空';
            return false;
        }

        if (!isset($data['address'])) {
            $this->error = '用户地址不能为空';
            return false;
        }

        if (empty($data['type_id'])) {
            $this->error = '预约类型未选择';
            return false;
        }

        if (empty($data['appointment_date'])) {
            $this->error = '预约日期未选择';
            return false;
        }

        $data['appointment_date'] = strtotime($data['appointment_date']);

        if (empty($data['time_id'])) {
            $this->error = '时间点未选择';
            return false;
        }

        $data['time_id'] = implode(',',$data['time_id']);

        if (empty($data['service_id'])) {
            $this->error = '服务人员未选择';
            return false;
        }

        if (empty($data['offline_name'])) {
            $this->error = '请输入服务内容';
            return false;
        }

        if (empty($data['money'])) {
            $data['money'] = 0;
        }

        $serverName = Db("server_user")->where("user_id", $data['service_id'])
            ->where('wxapp_id', self::$wxapp_id)->value('real_name');
        if (empty($serverName)) {
            $this->error = '服务人员信息未找到';
            return false;
        }

        $data['service_name'] = $serverName;
        $data['is_offline'] = 1;

        $order = [
            'order_no' => OrderService::createOrderNo(),
            'total_price' => $data['money'],
            'order_price' => $data['money'],
        ];
        Db::startTrans();

        $use_time = $data['use_time'];
        $order_id = Db("order")->insertGetId($order);
        $data['user_order_id'] = $order_id;
        $data['wxapp_id'] = self::$wxapp_id;

        $status = $this->allowField(true)->save($data);

        $ServiceModel = new ServiceModel();
        $ServiceModel->add_service($this->id, $data['service_id'], $data['money'], $use_time, $data['num']);

        if ($status && $order_id > 0) {
            Db::commit();
            return true;
        } else {
            Db::rollback();
            return false;
        }
    }

    /**
     * 编辑商品
     * @param $data
     * @return bool|mixed
     */
    public function edit($data)
    {
        if (empty($data['appointment_date'])) return false;

        $order = Db("order")->where('order_id', $data['user_order_id'])->find();
        if ($order && abs($data['money'] - $order['order_price']) > 0.01) {
            Db("order")->where('order_id', $data['user_order_id'])->update([
                'order_price' => $data['money'],
                'total_price' => $data['money'],
            ]);
        }

        $data['appointment_date'] = isset($data['appointment_date']) ? strtotime($data['appointment_date']) : '';
        $data['time_id'] = implode(',',$data['time_id']);
        $ServiceModel = new ServiceModel();
        $ServiceModel->add_service($this->id, $data['service_id'], $data['money'], $data['use_time'], $data['num']);

        return $this->allowField(['order_id', 'user_name', 'user_phone'
            , 'service_id', 'time_id', 'appointment_date'
            , 'type_id', 'update_time','offline_name','offline_remark','offline_from'])
            ->save($data, ['order_id' => $data['order_id']]);
    }

    /**
     * 类型详情
     * @param $grade_id
     * @param array $with
     * @return static|null
     * @throws \think\exception\DbException
     */
    public static function detail($order_id, $with = [])
    {
        return static::get($order_id, $with);
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }
}